from flask import Blueprint, request, current_app
from app.utils.response_util import ResponseUtil

bp = Blueprint('chat', __name__, url_prefix='/api/chat')

@bp.route('', methods=['POST'])
def chat():
    """处理聊天请求，支持文本和图片输入"""
    try:
        data = request.get_json()
        query = data.get('query')

        if not query:
            return ResponseUtil.missing_params("缺少查询文本")

        # 构建消息内容
        message_content = [{"type": "text", "text": query}]
        image_url = data.get('image_url')
        if image_url:
            message_content.append({
                "type": "image_url",
                "image_url": {"url": image_url}
            })

        # 调用 OpenAI API
        client = current_app.openai_client
        completion = client.chat.completions.create(
            model="qwen-vl-plus",
            messages=[{
                "role": "user",
                "content": message_content
            }]
        )

        response_content = completion.choices[0].message.content
        return ResponseUtil.success(data={"response": response_content})

    except Exception as e:
        return ResponseUtil.error(str(e))